﻿using System;
using System.Data;
using System.Windows.Forms;
using Lib.CommonForm;

namespace AUI
{
    public partial class frmRolesList : FormBase
    {
        DataTable dtUser = null;
        string _roleName = "";
        string _roleId = "";

        public frmRolesList(string formText)
        {
            InitializeComponent();
            
            if (formText != "")
            {
                this.Text = formText;
                this.TabText = formText;
            }
            _listRole = tbl_RoleRight_Controller.Instance().GetInfo("VaiTro");

            //Trường hợp người dùng bị mất hết quyền trong vai trò Administrator hoặc mất hết vai trò thì set mặc định như sau
            if (FormGlobals.isAdmin)
            {
                _listRole = new tbl_RoleRight_Info();
                _listRole.ModuleId = "VaiTro";
                _listRole.ViewRight = true;
                _listRole.CreateRight = true;
                _listRole.UpdateRight = true;
                _listRole.DeleteRight = true;
                _listRole.PrintRight = true;
            }

            btnAdd_Role.Enabled = _listRole.CreateRight;
            btnEdit_Role.Enabled = (_listRole.ViewRight || _listRole.UpdateRight);
            btnListAddUser_UserInRole.Enabled = _listRole.UpdateRight;
            btnDelete_Role.Enabled = _listRole.DeleteRight;

            //
            FormGlobals.dgv_SelectionMode_FullRowSelect(dgvRoles);
            dgvRoles.BorderStyle = BorderStyle.FixedSingle;
            //dgvRoles.ColumnHeadersVisible = false;
            FormGlobals.dgv_AddColumn_TextBox(dgvRoles, "RoleName", "Tên vai trò", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvRoles, "RoleId", "Vai trò", "", 1, false, false);
            FormGlobals.dgv_ColumnsSortMode(dgvRoles, DataGridViewColumnSortMode.NotSortable);
            dgvRoles.Columns["RoleName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            Roles_GetAll();
            //
            FormGlobals.dgv_SelectionMode_FullRowSelect(dgvUsers);
            dgvUsers.BorderStyle = BorderStyle.FixedSingle;
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "UserName", "Tên đăng nhập", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "EmployeeCode", "Mã nhân viên", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "EmployeeName", "Họ và tên", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "Position", "Chức vụ", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "BranchName", "Đơn vị", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "DepartmentName", "Bộ phận", "", 1, true, true);
            FormGlobals.dgv_AddColumn_Button(dgvUsers, "btnDelete", "", "", 30, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvUsers, "UserId", "", "", 1, false, false);

            dgvUsers.Columns["btnDelete"].ToolTipText = "Xóa";

            FormGlobals.dgv_ColumnsSortMode(dgvUsers, DataGridViewColumnSortMode.Programmatic);
            foreach (DataGridViewColumn item in dgvUsers.Columns)
            {
                if (item.Name != "btnDelete")
                    item.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }


            //

            FormGlobals.dgv_SelectionMode_CellSelect(dgvRoleRights, false);
            dgvRoleRights.BorderStyle = BorderStyle.FixedSingle;
            FormGlobals.dgv_AddColumn_TextBox(dgvRoleRights, "ModuleName", "Tên chức năng", "", 400, true, true);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "ViewRight", "Xem", "", 80, true, !_listRole.UpdateRight);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "CreateRight", "Thêm", "", 60, true, !_listRole.UpdateRight);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "UpdateRight", "Sửa", "", 60, true, !_listRole.UpdateRight);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "DeleteRight", "Xóa", "", 60, true, !_listRole.UpdateRight);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "PrintRight", "Xuất", "", 60, true, !_listRole.UpdateRight);
            FormGlobals.dgv_AddColumn_CheckBox(dgvRoleRights, "ModuleID", "ModuleID", "", 60, false, !_listRole.UpdateRight);

            FormGlobals.dgv_ColumnsSortMode(dgvRoleRights, DataGridViewColumnSortMode.NotSortable);

            dgvRoleRights.Columns["ModuleName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            //
            _IsLoading = false;
        }
        public override void Show_Form()
        {
            this.Show();
        }

        void Roles_GetAll()
        {
            _IsLoading = true;
            dgvRoles.DataSource = tbl_Roles_Controller.Instance().GetAll();
            _IsLoading = false;
        }

        void Users_GetUsersInRoles()
        {
            if (_IsLoading) return;

            if (dgvRoles.SelectedRows.Count > 0)
            {
                dtUser = tbl_Users_Controller.Instance().GetUsersInRoles1(_roleName);
                dgvUsers.DataSource = dtUser;
            }
        }

        void RoleRights_GetByRole()
        {
            if (_IsLoading) return;

            if (dgvRoles.SelectedRows.Count > 0)
            {
                dgvRoleRights.DataSource = tbl_RoleRight_Controller.Instance().GetByRoleName(_roleName);
            }
        }

        void GetRowValue()
        {
            if (_IsLoading) return;
            if (dgvRoles.SelectedRows.Count > 0)
            {
                _roleName = Globals.ToString(dgvRoles.SelectedRows[0].Cells["RoleName"].Value);
                _roleId = Globals.ToString(dgvRoles.SelectedRows[0].Cells["RoleId"].Value);
            }
            else
            {
                _roleName = "";
                _roleId = "";
            }
        }

        private void btnAddRole_Click(object sender, EventArgs e)
        {
            frmRoleInfo f = new frmRoleInfo("", "");
            if (f.ShowDialog(this) == DialogResult.OK)
            {

                Roles_GetAll();
                GetRowValue();
                Users_GetUsersInRoles();
                RoleRights_GetByRole();
            }
        }

        private void btnEditRole_Click(object sender, EventArgs e)
        {
            if (dgvRoles.SelectedRows.Count > 0)
            {
                frmRoleInfo f = new frmRoleInfo(_roleId, _roleName);
                if (f.ShowDialog(this) == DialogResult.OK)
                {

                    Roles_GetAll();
                    //Re selection on datagridview
                    FormGlobals.dgv_ReSelection(dgvRoles, "RoleId", _roleId);
                }
            }
        }

        private void btnDelRole_Click(object sender, EventArgs e)
        {
            if (dgvRoles.SelectedRows.Count > 0)
            {
                if (FormGlobals.Message_Confirm(UIMessage.QUESTION_DELETE))
                {
                    try
                    {
                        if (!tbl_Roles_Controller.Instance().DeleteRole(_roleName))
                        {
                            FormGlobals.Message_Error(new Exception( UIMessage.DETETE_ERROR));
                        }
                        else
                        {
                            FormGlobals.Message_InTaskbar(UIMessage.DETETE_COMPLETE);
                            Roles_GetAll();
                            GetRowValue();
                            Users_GetUsersInRoles();
                            RoleRights_GetByRole();
                        }
                    }

                    catch (Exception ex)
                    {
                        FormGlobals.Message_Error(ex);
                    }

                }
            }

        }

        private void btnAddUserInRole_Click(object sender, EventArgs e)
        {
            //if (dgvRoles.SelectedRows.Count > 0)
            //{

            //    int branchID = 0;
            //    frmUsersList f = new frmUsersList("Chọn người dùng", true, branchID, "");
            //    if (f.ShowDialog() == DialogResult.OK)
            //    {
            //        int n = dgvUsers.RowCount;
            //        bool allowAdd = true;
            //        for (int i = 0; i < n; i++)
            //        {
            //            if (Globals.ToString(f.dr["UserName"]) == Globals.ToString(dgvUsers.Rows[i].Cells["UserName"].Value))
            //            {
            //                FormGlobals.Message_InTaskbar("Người dùng này đã có trong danh sách rồi.");
            //                allowAdd = false;
            //                break;
            //            }
            //        }
            //        if (allowAdd)
            //        {
            //            try
            //            {
            //                //Add user to roles
            //                tbl_Roles_Controller.Instance().AddUserToRole(Globals.ToString(f.dr["UserName"]), _roleName);

            //                DataRow myrow = dtUser.NewRow();
            //                myrow = f.dr;
            //                dtUser.ImportRow(myrow);
            //                dtUser.AcceptChanges();
            //                dgvUsers.DataSource = dtUser;
            //                //
            //            }
            //            catch (Exception ex)
            //            {
            //                FormGlobals.Message_Error(ex);
            //            }

            //        }
            //    }
            //    this.Activate();
            //}
        }


        private void frmRolesList_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case (Keys.Control | Keys.N):
                    btnAdd_Role.PerformClick();
                    break;
                case (Keys.F3):
                    btnEdit_Role.PerformClick();
                    break;
            }
        }


        private void dgvRoles_SelectionChanged(object sender, EventArgs e)
        {
            if (!_IsLoading)
            {
                GetRowValue();
                Users_GetUsersInRoles();
                RoleRights_GetByRole();

                //dgvRoles.Refresh();
                //if (this.Handle != null)
                //{
                //    this.BeginInvoke((MethodInvoker)this.ShowDesktopAlert);
                //}
            }
        }
        private void ShowDesktopAlert()
        {
            // Code for displaying alert     
        }

        private void dgvUsers_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgv_ColumnHeaderMouseClick(sender, e, delegate { Users_GetUsersInRoles(); });
        }

        private void dgvRoleRights_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgv_ColumnHeaderMouseClick(sender, e, delegate { RoleRights_GetByRole(); });
        }

        private void dgvUsers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvUsers.Columns[e.ColumnIndex] == dgvUsers.Columns["btnDelete"] && e.RowIndex >= 0)
            {
                if (FormGlobals.Message_Confirm(UIMessage.QUESTION_DELETE))
                {
                    try
                    {
                        //Xoa DB truoc

                        tbl_Roles_Controller.Instance().RemoveUserFromRole(dgvUsers.Rows[e.RowIndex].Cells["UserName"].Value.ToString(), _roleName);
                        //
                        dtUser.Rows.RemoveAt(e.RowIndex);
                        dtUser.AcceptChanges();
                        dgvUsers.DataSource = dtUser;
                    }

                    catch (Exception ex)
                    {
                        FormGlobals.Message_Error(ex);
                    }
                }
            }
        }

        private void dgvRoleRights_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvRoleRights_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvRoleRights.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dgvRoleRights_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex <= 0)
                return;

            if (!_listRole.UpdateRight) return;

            if (dgvRoleRights.DataSource != null)
            {
                tbl_RoleRight_Info info = new tbl_RoleRight_Info();
                info.FillDataProperty(FormGlobals.dgv_GetDataRow(dgvRoleRights));
                info.RoleId = _roleId;
                try
                {
                    tbl_RoleRight_Controller.Instance().Append(info);
                }
                catch (Exception ex)
                {
                    FormGlobals.Message_Error(ex);
                }
            }
        }

        private void dgvRoleRights_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

        }
    }
}
